package com.deyou.fragment;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.deyou.Constants;
import com.deyou.R;
import com.deyou.activity.HouseSearchActivity;
import com.deyou.adapter.HomePageRecommendAdapter;
import com.deyou.adapter.MyGridViewAdapter;
import com.deyou.adapter.MyViewPagerAdapter;
import com.deyou.base.BaseFragment;
import com.deyou.callback.ServerApi;
import com.deyou.event.LoginEvent;
import com.deyou.model.HomeDataBean;
import com.deyou.model.HomePageCityBean;
import com.deyou.model.LzyResponse;
import com.deyou.model.SimpleResponse;
import com.deyou.util.AESUtil;
import com.deyou.util.AndroidUtils;
import com.deyou.util.GlideImageLoader;
import com.deyou.util.SPUtils;
import com.deyou.util.Urls;
import com.deyou.widget.CustomViewPager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class HomePageFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.home_banner)
    Banner homeBanner;
    @BindView(R.id.tv_hot_city)
    TextView tvHotCity;
    @BindView(R.id.tv_recommond)
    TextView tvRecommond;
    @BindView(R.id.recommond_recyclerview)
    RecyclerView recommondRecyclerview;
    @BindView(R.id.tv_homestay)
    TextView tvHomestay;
    @BindView(R.id.btn_search)
    TextView btnSearch;
    @BindView(R.id.viewpager)
    CustomViewPager viewpager;
    @BindView(R.id.points)
    LinearLayout hotCityDotLayout;
    @BindView(R.id.home_stay_viewpager)
    CustomViewPager homeStayViewpager;
    @BindView(R.id.home_stay_points)
    LinearLayout homeStayDotLayout;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.hot_vp_layout)
    RelativeLayout hotVpLayout;
    @BindView(R.id.homestay_vp_layout)
    RelativeLayout homestayVpLayout;
    @BindView(R.id.root_layout)
    RelativeLayout rootLayout;
    @BindView(R.id.scroll_view)
    ScrollView scrollView;
    Unbinder unbinder1;

    private Context mContext;
    Unbinder unbinder;
    private boolean isRefresh = false;

    private List<String> bannerUrls = new ArrayList<>();
    private HomePageRecommendAdapter recommendAdapter;
    private int mPageSize = 6;

    public HomePageFragment() {
    }

    public static HomePageFragment newInstance(String param1, String param2) {
        HomePageFragment fragment = new HomePageFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        this.mContext = context;
        EventBus.getDefault().register(this);
        super.onAttach(context);
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_page, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initData() {
        refreshLayout.setColorSchemeColors(Color.RED, Color.BLUE, Color.GREEN);
        refreshLayout.setOnRefreshListener(this);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 510);
        homeBanner.setLayoutParams(params);
        recommendAdapter = new HomePageRecommendAdapter(mContext);
        getHomeData();
        initListener();
    }

    private void initListener() {
    }

    private void getHomeData() {
        JSONObject object = new JSONObject();
        try {
            object.put("userId", SPUtils.getStringByKey(getActivity(), Constants.UserId));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String paramJson = object.toString();

        Type type = new TypeToken<LzyResponse<HomeDataBean>>() {
        }.getType();
        ServerApi.<LzyResponse<HomeDataBean>>getData(type, Urls.getHomeData, "", AESUtil.encrypt(paramJson))//
                .subscribeOn(Schedulers.io())//
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        showLoading();
                    }
                })//
                .map(new Function<LzyResponse<HomeDataBean>, HomeDataBean>() {
                    @Override
                    public HomeDataBean apply(@NonNull LzyResponse<HomeDataBean> response) throws Exception {
                        return response.data;
                    }
                })//
                .observeOn(AndroidSchedulers.mainThread())  //
                .subscribe(new Observer<HomeDataBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                    }

                    @Override
                    public void onNext(@NonNull HomeDataBean homeDataBeen) {
                        if (isRefresh)
                            setRefreshing(false);
                        else
                            dismissLoading();
                        if (null != homeDataBeen) {
                            if (null != homeDataBeen.picList && homeDataBeen.picList.size() > 0) {
                                dealBanner(homeDataBeen.picList);
                            } else {
                                handler.sendEmptyMessage(2);
                            }
                            if (null != homeDataBeen.hotcityList && homeDataBeen.hotcityList.size() > 0) {
                                initGridViewPager(viewpager, hotCityDotLayout, 1, homeDataBeen.hotcityList);
                                tvHotCity.setVisibility(View.VISIBLE);
                                hotVpLayout.setVisibility(View.VISIBLE);
                            } else {
                                handler.sendEmptyMessage(3);
                            }
                            if (null != homeDataBeen.hotcitychinaList && homeDataBeen.hotcitychinaList.size() > 0) {
                                initGridViewPager(homeStayViewpager, homeStayDotLayout, 2, homeDataBeen.hotcitychinaList);
                                tvHomestay.setVisibility(View.VISIBLE);
                                homestayVpLayout.setVisibility(View.VISIBLE);
                            } else {
                                handler.sendEmptyMessage(4);
                            }
                            if (null != homeDataBeen.houseresourceList && homeDataBeen.houseresourceList.size() > 0) {
                                recommondRecyclerview.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
                                recommendAdapter.setData(homeDataBeen.houseresourceList);
                                recommondRecyclerview.setAdapter(recommendAdapter);
                                tvRecommond.setVisibility(View.VISIBLE);
                                recommondRecyclerview.setVisibility(View.VISIBLE);
                            } else {
                                handler.sendEmptyMessage(5);
                            }
                        } else {
                            handler.sendEmptyMessage(6);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        e.printStackTrace();            //请求失败
                        if (isRefresh)
                            setRefreshing(false);
                        else
                            dismissLoading();
                    }

                    @Override
                    public void onComplete() {
                        dismissLoading();
                    }
                });
    }

    /**
     * 热门城市/民宿中国接口具体处理
     *
     * @param view
     * @param dotView
     * @param cityType
     */
    private void initGridViewPager(final CustomViewPager view, final LinearLayout dotView, int cityType, List<HomeDataBean.HotCity> homePageCityBeen) {
        //总的页数向上取整
        final int hotTotalPage = (int) Math.ceil(homePageCityBeen.size() * 1.0 / mPageSize);
        ArrayList<View> viewPagerList = new ArrayList<View>();
        for (int i = 0; i < hotTotalPage; i++) {
            //每个页面都是inflate出一个新实例
            final GridView gridView = (GridView) View.inflate(getActivity(), R.layout.item_gridview, null);
            MyGridViewAdapter gridViewAdapter = new MyGridViewAdapter(getActivity());
            gridViewAdapter.setLists(homePageCityBeen);
            gridViewAdapter.setmIndex(i);
            gridViewAdapter.setmPagerSize(mPageSize);
            gridView.setAdapter(gridViewAdapter);
            //添加item点击监听
//            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//
//                @Override
//                public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
//                    Object obj = gridView.getItemAtPosition(position);
//                    if (obj != null && obj instanceof HomePageCityBean) {
//                        Toast.makeText(getActivity(), ((HomePageCityBean) obj).regionName, Toast.LENGTH_SHORT).show();
//                    }
//                }
//            });
            viewPagerList.add(gridView);
        }
        //设置ViewPager适配器
        if (homePageCityBeen.size() < 4) {
            view.setRows(1);
        } else {
            view.setRows(2);
        }
        view.setAdapter(new MyViewPagerAdapter(viewPagerList));

        dotView.removeAllViews();
        //添加小圆点
        final ImageView[] ivPoints = new ImageView[hotTotalPage];
        for (int i = 0; i < hotTotalPage; i++) {
            ivPoints[i] = new ImageView(getActivity());
            if (i == 0) {
                ivPoints[i].setImageResource(R.drawable.dot_selected);
            } else {
                ivPoints[i].setImageResource(R.drawable.dot_unselected);
            }
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(30, 30);
            ivPoints[i].setLayoutParams(params);
            ivPoints[i].setPadding(8, 8, 8, 8);
            dotView.addView(ivPoints[i]);
        }

        //设置ViewPager的滑动监听，主要是设置点点的背景颜色的改变
        view.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < hotTotalPage; i++) {
                    if (i == position) {
                        ivPoints[i].setImageResource(R.drawable.dot_selected);
                    } else {
                        ivPoints[i].setImageResource(R.drawable.dot_unselected);
                    }
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(LoginEvent event) {
        if (event.isLogin()) {
            onRefresh();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.btn_search)
    public void onViewClicked() {
        AndroidUtils.startNextActivity(getActivity(), HouseSearchActivity.class, null, false);
    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        homeBanner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        homeBanner.stopAutoPlay();
    }

    private void dealBanner(List<HomeDataBean.Banner> picList) {
        if (null != bannerUrls)
            bannerUrls.clear();
        for (HomeDataBean.Banner banner : picList) {
            if (null != banner) {
                bannerUrls.add(Urls.ImageBaseUrl + "hometurns/" + banner.hometurnsPic);
            }
        }
        handler.sendEmptyMessage(1);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    homeBanner.setVisibility(View.VISIBLE);
                    //设置banner样式
                    homeBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
                    homeBanner.setImageLoader(new GlideImageLoader());
                    homeBanner.setImages(bannerUrls);
                    //设置banner动画效果
                    homeBanner.setBannerAnimation(Transformer.DepthPage);
                    homeBanner.setIndicatorGravity(BannerConfig.CENTER);
                    homeBanner.start();
                    break;
                case 2: // 没有轮播图
                    homeBanner.setVisibility(View.GONE);
                    break;
                case 3: // 没有热门城市
                    tvHotCity.setVisibility(View.GONE);
                    hotVpLayout.setVisibility(View.GONE);
                    break;
                case 4: // 没有民宿中国
                    tvHomestay.setVisibility(View.GONE);
                    homestayVpLayout.setVisibility(View.GONE);
                    break;
                case 5: // 没有为你推荐
                    tvRecommond.setVisibility(View.GONE);
                    recommondRecyclerview.setVisibility(View.GONE);
                    break;
                case 6: // 完全没用数据
                    break;

            }
        }
    };

    @Override
    public void onRefresh() {
        isRefresh = true;
        getHomeData();
    }

    public void setRefreshing(final boolean refreshing) {
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(refreshing);
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder1 = ButterKnife.bind(this, rootView);
        return rootView;
    }
}
